package com.zlx.exchange.order.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.json.JSONObject;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.rabbitmq.client.Channel;
import com.zlx.exchange.domain.entity.Order;
import com.zlx.exchange.order.dao.OrderDao;
import com.zlx.exchange.order.service.OrderService;
import lombok.SneakyThrows;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageInfo;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.ResponseEntity;
import com.github.pagehelper.PageHelper;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * (Order)表服务实现类
 *
 * @author makejava
 * @since 2023-09-04 21:07:23
 */
@Transactional
@Service("orderService")
public class OrderServiceImpl implements OrderService {
    private static final String GATEWAY_URL =
            "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT = "JSON";
    private static final String CHARSET = "UTF-8";
    //签名方式
    private static final String SIGN_TYPE = "RSA2";
    @Resource
    private OrderDao orderDao;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 通过ID查询单条数据
     *
     * @param orderId 主键
     * @return 返回体
     */
    @Override
    public ResponseEntity<?> queryById(Long orderId) {
        this.orderDao.selectById(orderId);
        return ResponseEntity.ok("通过id查询，请加入返回体");
    }

    private Object getToken(String token) {
        JWT jwt = JWTUtil.parseToken(token);
        return  jwt.getPayload("userId");
    }

    /**
     * 分页查询
     *
     * @param order    筛选条件
     * @param pageNum  分页页数
     * @param pageSize 分页总页数
     * @return 查询结果
     */
    @Override
    public ResponseEntity<?> queryByPage(Order order, Integer pageNum, Integer pageSize, Date timeBefore, Date timeAfter) {
        PageHelper.startPage(pageNum, pageSize);
        return ResponseEntity.ok(new PageInfo<>(this.orderDao.selectList(new LambdaQueryWrapper<Order>().eq(StringUtils.isNotBlank(order.getGoods()), Order::getGoods, order.getGoods()).
                eq(Objects.isNull(order.getStatus()), Order::getStatus, order.getStatus()).between(ObjectUtils.isNotNull(timeAfter, timeBefore), Order::getCreateTime, timeAfter, timeBefore).
                eq(Objects.nonNull(order.getOrderId()), Order::getOrderId, order.getOrderId()
                )
        )));
    }

    /**
     * 新增数据
     *
     * @param order 实例对象
     * @return 返回体
     */
    @Override
    public ResponseEntity<?> insert(Order order) {
        this.orderDao.insert(order);
        return ResponseEntity.ok("插入一条数据，请加入返回体");
    }

    /**
     * 修改数据
     *
     * @param order 实例对象
     * @return 返回体
     */
    @Override
    public ResponseEntity<?> update(Order order) {
        this.orderDao.updateById(order);
        this.queryById(order.getOrderId());
        return ResponseEntity.ok("修改一条数据，请添加返回体");
    }

    /**
     * 通过主键删除数据
     *
     * @param orderId 主键
     * @return 返回体，判断是否成功
     */
    @Override
    public ResponseEntity<?> deleteById(Integer orderId) {
        boolean b = this.orderDao.deleteById(orderId) > 0;
        return ResponseEntity.ok("通过id删除一条数据，请加入返回体");
    }


    @Override
    public ResponseEntity<?> createOrder(Order order, String token, HttpServletResponse response, HttpServletRequest request) {
        RLock orderLock = redissonClient.getLock("orderLock");
        orderLock.lock();
        try {
            Snowflake snowflake = new Snowflake();
            order.setOrderId(snowflake.nextId());
            order.setStatus(false);
            order.setCreateTime(new Date());
            order.setUserId(Integer.parseInt(getToken(token).toString()));
            redisTemplate.opsForList().rightPushIfPresent("unpaid" + getToken(token), order.getOrderId());
            redisTemplate.opsForValue().set("order" + order.getOrderId(), order, 30, TimeUnit.MINUTES);
            //发送延时消息

        } finally {
            orderLock.unlock();
            System.out.println("订单"+order.getOrderId()+"创建成功");
        }
        //跳转到支付宝支付接口
        pay(order, response);
        rabbitTemplate.convertAndSend("delay_queue", request, message -> {
            message.getMessageProperties().setHeader("x-delay", 30 * 1000 * 60);
            System.out.println("发送延时消息");
            return message;
        });
        return ResponseEntity.ok("订单创建成功");
    }

    /**
     * 支付宝接口
     *
     * @param order
     * @param httpResponse
     * @throws Exception
     */
    @SneakyThrows
    public void pay(Order order, HttpServletResponse httpResponse) {
        // 1. 创建Client，通用SDK提供的Client，负责调用支付宝的API
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, "9021000123612031",
                "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC7dQ9ShJH6lysWBnUEesGVkIHBbbjuhRbXS0DVLRHuEpczkL3q9UuAOI6Y/xzU2+gaKzkM5PQfI8U0neA+QkixkSbb5NiXrzji5zcebFZxaonH5pcQnTF4PX8NSt93aiVI2SObM2hHMnp2+JA6texqJHqLfg/vZ+7BYwTpNKnANUR0w2pgjDupQqZjVyR8UtgWqD+qrcoLko4rd4dzu85Z9AKeSWeb7Q1oK72xXG/8Fs78qg7QNxgbat3q5dCKfaWviwe/DoxYJ9HLoOnmjUylFPCvsVL9bE7wqdJvMNEVDniXodlGsGvES6uB1qIzi/RbkR8URHOYY5j0uueDxVTTAgMBAAECggEANXNwdggFE94M1A/tR+S01C/LP9tIcwKR+7uideaPCUJVyMdJz/g3mg0GZAvCLdOyf9u5Pbr+/O4XKiSmL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+kv/wX9exPMUtkzi3/iXKtW3Tz9X0NzEJ9lD5KS3rfrpRXU="
                , FORMAT, CHARSET,
                "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzWLsTCbWb2wdDsmJLmm6hl4Um4FLUZuPXqJbLF6ifWpXVG42okLDgg/6y4vYJabuxf9+a+C3QEhvZLCwhG3rzMWX/cMaNRQcrgZ10sgszTM+eo9mKLSDwohbZrYIecmP5kiCcwfpCUdzANXw/Lu0kBtuVgsKILi3gzSP6fATQ2Brj387vqLBqG1ZLMSthvUIMwpozQf9S2pdPqKetfU0Pu0sxK5s30v7Zb0ICDPSkbsAxBdtcdqdcIAeoz5MC48XcYq+AKD3dJMVhtaezfWKWoqG3cIroB5/dxM9iQanyJT6QEkMirK0uohFETYP46c3r2rIwrvSbqeIx1XnLGOG+wIDAQAB",
                SIGN_TYPE);

        // 2. 创建 Request并设置Request参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();  // 发送请求的 Request类
        request.setNotifyUrl("http://muaqx9.natappfree.cc/alipay/notify");
        JSONObject bizContent = new JSONObject();
        bizContent.set("out_trade_no", order.getOrderId());  // 我们自己生成的订单编号
        bizContent.set("total_amount", order.getCounts()); // 订单的总金额
        bizContent.set("subject", order.getGoods());   // 支付的名称
        bizContent.set("product_code", "FAST_INSTANT_TRADE_PAY");  // 固定配置
        request.setBizContent(bizContent.toString());

        // 执行请求，拿到响应的结果，返回给浏览器
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    /**
     * 消费失败如何检测
     */
    /**
     * 将支付成功订单插入数据库
     * @Param order
     */
    /**
     * 支付宝接口回调
     *
     * @param request
     * @return
     * @throws Exception
     */
    @SneakyThrows
    @RabbitHandler
    @RabbitListener(queues = "delay_queue")
    public Boolean payNotify(HttpServletRequest request, Channel channel, @Payload Message message) {
        if (Objects.isNull(message.getMessageProperties())) {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            return false;
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        System.out.println("接受到的消息为" + new String(message.getBody(), "UTF-8"));
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                System.out.println(name + " = " + request.getParameter(name));
            }

            String outTradeNo = params.get("out_trade_no");
            String gmtPayment = params.get("gmt_payment");
            String alipayTradeNo = params.get("trade_no");

            String sign = params.get("sign");
            String content = AlipaySignature.getSignCheckContentV1(params);
            boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign,
                    "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC7dQ9ShJH6lysWBnUEesGVkIHBbbjuhRbXS0DVLRHuEpczkL3q9UuAOI6Y/xzU2+gaKzkM5PQfI8U0neA+QkixkSbb5NiXrzji5zcebFZxaonH5pcQnTF4PX8NSt93aiVI2SObM2hHMnp2+JA6texqJHqLfg/vZ+7BYwTpNKnANUR0w2pgjDupQqZjVyR8UtgWqD+qrcoLko4rd4dzu85Z9AKeSWeb7Q1oK72xXG/8Fs78qg7QNxgbat3q5dCKfaWviwe/DoxYJ9HLoOnmjUylFPCvsVL9bE7wqdJvMNEVDniXodlGsGvES6uB1qIzi/RbkR8URHOYY5j0uueDxVTTAgMBAAECggEANXNwdggFE94M1A/tR+S01C/LP9tIcwKR+7uideaPCUJVyMdJz/g3mg0GZAvCLdOyf9u5Pbr+/O4XKiSmLzp5PeB0oxjCxaWZ4+En703W7CoDtXNDueIInA907dZel881aGs54uQqpLp4/vlrLsJ28eEK7EF6y7nn806HtPNmP76zRxhTd5Z6GCUQ+XwVLWOxLHuyMxrKN2Q1FtFFZn7gso5S17BE8PjgLaUeSeGccThN2U1FOjfdIUCvjhDFPQwxTRGzj0LyhDykH64Cx2JnGd4W4aycKzFr92289u83+URCP2VDne+y91WqKZbafZw8EeWHYj4xu0DiOADsrcPKUQKBgQDsYUC8B30fCjWEOrc3i1uYpTcxK72wBR3WSycCK7mskMXzK4QjizjZivtgqhvm5ZovzvEOnebHaZTqDAxdBzMVUOFzdphIgO8xoca4G9tIN35ZtEkYB0WUcG1VFd188mVVlXvxwP3N+UHGk9Uj1xThIpJONSOA5xs05n0GTFc7eQKBgQDLBES9D+s8zmhlntl0LMdt6LJFGq+kSlgbf2Z6TC7NjmVKbIWqMNFWzdBtezRyvxofV2+CmBXF56K7u+JaBVVasSx0TyrvbDabXUOh2N8p62aMrvG7pHCwbxa3EZ7awJx1MhM7YxM5wolRpPXqonV9hyRcrT3MmiZa63GA2IOzqwKBgQCe2BuwPzgNi8a6vNoyMSu0QBH+sO4fQtDyGD52bvuuwvrClhON7xic15BlPOrTFqeuSNokgGd8ya6QONh2C0iAooFeHevnjP0v1Q682btZpDD8BvK3eut+/K37512XgSwnfvRzWMU1jLJuxxkLpJUbVSgL9hmNnb/ipKCPgu17wQKBgD1cLOp3xUG7oRIV0OOsJRqzGi6Iwk2FqtukxfRw0jSOtU6pPj0SRDNYQYbVliSYXezbIHj4PpxyRl03jFJpCkM/CZCd3PxAWMDcj3R7d/fTjks3FRkBuo2ZBeSPDtRPIvrJB8cLSuRKR/bFRQ6Fy70E+5iHRAZzEOSqBMRMrIHBAoGAYjpcLgDO7L3Mo3uWFIDiyy/JbzcjPikwoGkR1w4O1iR8t4Vu0jNrYw9xB+q4hE1yI9Hmg6CXb8ssCvhvRF42KD7qg/SH1/Ip/+Wij0gOasMdVYL5A49fqiNukhQw+kv/wX9exPMUtkzi3/iXKtW3Tz9X0NzEJ9lD5KS3rfrpRXU="
                    , "UTF-8"); // 验证签名
            // 支付宝验签
            if (checkSignature) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));

                // 查询订单
//                QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
//                queryWrapper.eq("order_id", outTradeNo);
//
////
//                if (orders != null) {
//                    orders.setAlipayNo(alipayTradeNo);
//                    orders.setPayTime(new Date());
//                    orders.setState("已支付");
//                    ordersMapper.updateById(orders);
//                }
//            }
            }

        }
        return true;
    }

    /**
     * 从redis查看付过款的订单
     *
     * @param token
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public ResponseEntity<?> queryUnpaid(String token, Integer pageNum, Integer pageSize) {
        if (redisTemplate.hasKey("unpaid" + getToken(token))) {
            Long size = redisTemplate.opsForList().size("unpaid" + getToken(token));
            List<Object> list = redisTemplate.opsForList().range("unpaid" + getToken(token), 0, size);
            //拼接orderVO
            return ResponseEntity.ok(list);
        }
        return ResponseEntity.ok("未查到未付款订单");
    }
}


